package cn.mhome.merchant.framework.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.mhome.merchant.entity.common.result.DealResult;
import cn.mhome.merchant.enums.CaptchaTypeEnum;
import cn.mhome.merchant.util.MD5;

/**
 * 登陆登出控制器
 * @author lvpeng
 */
@Controller
@RequestMapping("/system/common")
public class SysLoginController{
	protected static Logger logger = LoggerFactory
			.getLogger(SysLoginController.class);


	/**
	 * 登陆
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login", method = { RequestMethod.POST,
			RequestMethod.GET }, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String login(HttpServletRequest request) {
		
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token;
		try {
			token = new UsernamePasswordToken(URLDecoder.decode(account, "UTF-8"),
					MD5.crypt(password));
			
			currentUser.login(token);
			
			DealResult dealResult = new DealResult();
			dealResult.setDealcode(200);
			dealResult.setDealmsg("登陆成功");
		} catch (UnsupportedEncodingException e) {
			return "{\"dealcode\":300,\"dealmsg\":\""+e.getMessage()+"\"}";
		} catch(IncorrectCredentialsException e2){
			return "{\"dealcode\":300,\"dealmsg\":\""+e2.getMessage()+"\"}";
		}
		return "{\"dealcode\":200,\"dealmsg\":\"登陆成功\"}";
	}
	
	
	/***
	 * 
	 * logout:登出操作. <br/>
	 * 
	 * @return 登出操作
	 * @since 1.0
	 */
	@RequestMapping(value = "/logout", method = { RequestMethod.POST, RequestMethod.GET }, produces = {
			"text/json;charset=UTF-8" })
	@ResponseBody
	public String logout() {
		DealResult ret = new DealResult();
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		ret.setDealcode(200);
		return "{\"dealcode\":200,\"dealmsg\":\"登出成功\"}";
	}
	
    /**
     * 获取验证码
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
	@RequestMapping(value = "/captcha", method = {
			RequestMethod.GET,RequestMethod.POST }, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public void captcha(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        outputCaptcha(CaptchaTypeEnum.CHECK_CODE_KEY.getMsg(),request, response);
    }
	
	
	
	public static void outputCaptcha(String checkCodeKey, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int width = 100, height = 30;
		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Font mFont = new Font("Arial Black", Font.PLAIN, 16);
		Graphics g = bufferedImage.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(245, 256));
		g.fillRect(1, 1, width - 1, height - 1);
		g.setColor(new Color(102, 102, 102));
		g.drawRect(0, 0, width - 1, height - 1);
		g.setFont(mFont);
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 150; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			g.drawLine(x, y, x + xl, y + yl);
		}
		for (int i = 0; i < 70; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(12) + 1;
			int yl = random.nextInt(6) + 1;
			g.drawLine(x, y, x - xl, y - yl);
		}
		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String tmp = String.valueOf(getRandomChar());
			sRand += tmp;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			g.setFont(new Font("Times New Roman", Font.BOLD + Font.ITALIC, 30));
			g.drawString(tmp, 10 + 20 * i, 25);
		}

		HttpSession session = request.getSession();
		session.setAttribute(checkCodeKey, sRand);
		g.dispose();

		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		ServletOutputStream responseOutputStream = response.getOutputStream();

		// 输出图象到页面
		ImageIO.write(bufferedImage, "JPEG", responseOutputStream);

		// 以下关闭输入流！
		responseOutputStream.flush();
		responseOutputStream.close();

	}

	private static Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private static char getRandomChar() {
		char cha1;
		char cha2;
		cha1 = '0';
		cha2 = '9';
		return (char) (cha1 + Math.random() * (cha2 - cha1 + 1));
	}
}
